<template>
	<!-- 角色列表页面 -->
	<echelon-solutions>
		<!-- 这里是顶部导航栏 -->
		<skyline-navigation title="权限管理"> </skyline-navigation>
		<!-- 这里是中间区域 -->
		<central-hub>
			<MyPopup v-model="popupVisible">
				<MyForm :fields="formFields" @submit="popupSubmitForm" submit-text="提交"></MyForm>
			</MyPopup>
			<MyPopup v-model="updateVisible">
				<MyForm :fields="updateFormFields" @submit="updateSubmitForm" submit-text="提交"></MyForm>
			</MyPopup>
			<view >
				<view class="flexGap">
					<button type="primary" @click="handlePopupAdd()">新增</button> 
				</view>
				<MyTreeTable :columns="columnsData" :dataSource="tableData"  style="zoom: .6;">
					<template #operate="{ data }">
						<view class="flexGap">
							<button type="primary" @click="handleEdit(data)">编辑</button>
							<button type="warn" @click="handleDelete(data)">删除</button>
						</view>
					</template>
				</MyTreeTable>
			</view>
		</central-hub>
	</echelon-solutions>
</template>

<script>
	export default {
		methods: {
			popupSubmitForm(formData) {
				this.$createPublic('permission', formData, async () => {
					this.handlePopupAdd();
					this.tableData = await this.$listPublic('permission');
				})
			},
			// 修改
			handleUpdate() {
				this.updateVisible = !this.updateVisible;
			},
			// 提交修改
			updateSubmitForm(formData) {
				this.$updatePublic('permission', formData, async () => {
					this.handleUpdate();
					this.tableData = await this.$listPublic('permission');
				})
			},
			// 新增
			handlePopupAdd() {
				this.popupVisible = !this.popupVisible;
			},
			// 修改
			handleEdit(data) {
				const arr = this.formFields.map(v => {
					v.value = data[v.name];
					return v;
				});
				this.updateFormFields = [{
					label: "修改id",
					type: "text",
					name: "id",
					value: data.id,
					required: true,
					disabled: true,
				}, ...arr];
				this.handleUpdate();
			},
			// 删除
			handleDelete(data) {
				this.$removePublic('permission', data, async () => {
					this.tableData = await this.$listPublic('permission');
				});
			}, 
		},
		onLoad() {
			this.$listPublic('permission', {}, data => {
				this.tableData = data;
			})
		},
		data() {
			return {
				popupVisible: false,
				updateVisible: false,
				updateFormFields: [],
				formFields: [{
						label: "权限的名称",
						type: "text",
						name: "name",
						value: "",
						required: true
					},
					{
						label: "描述",
						type: "text",
						name: "description",
						value: "",
						required: true
					}
				],
				columnsData: [{
						title: 'ID',
						key: 'id',
						fixed: 'left',
					},
					{
						title: '权限的名称',
						key: 'name'
					},
					{
						title: '描述',
						key: 'description'
					},
					{
						title: '操作',
						key: 'operate',
						fixed: '',
					}
				],
				tableData: []
			}
		}
	}
</script>
<style scoped>
	.central-hub-h {
		height: calc(var(--central-hub-h) - var(--my-tab-safe-area));
	}

	.flexGap {
		padding: 6px;
		box-sizing: border-box;
	}
</style>